<template>
  <div class="square-list-item">
    <div class="item-content" @click="handleTaskDetail">
      <div class="left-content">
        <span @click="handleTaskDetail">
          <el-image :src="showData.projectLogo || '/src/assets/img/task.png'" />
        </span>
      </div>
      <div class="right-content">
        <div class="content-head">
          <span v-if="showData.taskState == null" @click="handleTaskDetail" class="head-title">{{
            showData.taskName
          }}</span>
          <span v-else @click="handleTaskDetail" class="head-title-task">{{
            showData.taskName
          }}</span>
          <div class="tag-container">
            <span class="iconfont">
              <el-icon><Coin /></el-icon> {{ showData.taskScore }}
            </span>
            <span
              v-if="
                showData.taskState == null &&
                projectUserId === useUserStore().userMessage.userId &&
                useUserStore().userMessage.userId !== ''
              "
              class="tag"
            >
              <el-tag>我发布的任务</el-tag>
            </span>
            <span
              v-if="
                showData.taskState == null &&
                usersIdList.includes(useUserStore().userMessage.userId)
              "
              class="tag"
            >
              <el-tag type="success">我投标的任务</el-tag>
            </span>
          </div>
        </div>
        <div class="content-body">
          <div>
            项目类型：<span
              v-for="type in getProjectTypes(showData.projectType)"
              :key="type"
              style="margin-right: 5px"
            >
              <el-tag type="info">{{ type }}</el-tag>
            </span>
          </div>
          <div>
            人员需求：<span v-for="role in projectRoles" :key="role" style="margin-right: 5px">
              <el-tag type="info">{{ role }}</el-tag>
            </span>
          </div>
          <div>项目周期：{{ showData.taskPeriod === 0 ? 1 : showData.taskPeriod }} 天</div>
        </div>
        <div class="content-foot">
          <span>{{ formatTimeSince(showData.createDate) }}</span>
          <span v-show="showData.taskState == null">|</span>
          <span v-show="showData.taskState == null">投标人数：{{ bidderCount }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { codeToProjectType, codeToCharacters } from '@/mock/tasksquare'
import { getTaskDetail } from '@/service/taskdetail/taskdetail'
import { getProject } from '@/service/project/project'
import useUserStore from '@/store/user/user'
const router = useRouter()
const projectUserId = ref('')
const props = defineProps(['showData'])
const projectRoles = computed(() => getProjectRoles(props.showData.taskRole))
const fetchTaskDetail = async () => {
  const taskResponse = await getTaskDetail(props.showData.taskId)
  if (taskResponse.data) {
    const projectResponse = await getProject(taskResponse.data.projectsId)
    projectUserId.value = projectResponse.data?.userId
  }
}
onMounted(() => {
  fetchTaskDetail()
})
function getProjectTypes(typeCodes: string) {
  if (!typeCodes) return []
  return typeCodes.split('').map((code) => codeToProjectType[code])
}

function getProjectRoles(roleCodes: string) {
  if (!roleCodes) return []
  return roleCodes.split('').map((code) => codeToCharacters[code])
}

// 设置在新页面打开
const href = router.resolve({
  path: '/taskdetail/' + props.showData.taskId
})
const handleTaskDetail = () => {
  if (!useUserStore().userMessage.userId) {
    router.push('/login')
  } else {
    window.open(href.href)
  }
}

const formatTimeSince = (createDate: string) => {
  const now = dayjs()
  const created = dayjs(createDate)
  const diffSeconds = now.diff(created, 'second')
  const diffMinutes = now.diff(created, 'minute')
  const diffHours = now.diff(created, 'hour')
  const diffDays = now.diff(created, 'day')
  const diffWeeks = now.diff(created, 'week')
  const diffMonths = now.diff(created, 'month')
  const diffYears = now.diff(created, 'year')

  if (diffSeconds < 60 && diffSeconds > 0) {
    return `${diffSeconds}秒前发布`
  } else if (diffMinutes < 60 && diffMinutes > 0) {
    return `${diffMinutes}分钟前发布`
  } else if (diffHours < 24 && diffHours > 0) {
    return `${diffHours}小时前发布`
  } else if (diffDays < 7 && diffDays > 0) {
    return `${diffDays}天前发布`
  } else if (diffWeeks < 4.28 && diffWeeks > 0) {
    return `${diffWeeks}周前发布`
  } else if (diffMonths < 12 && diffMonths > 0) {
    return `${diffMonths}个月前发布`
  } else {
    return `${diffYears}年前发布`
  }
}

const bidderCount = computed(() => {
  if (!props.showData.taskBid) return 0
  else {
    return props.showData.taskBid.split(',').length
  }
})
const usersIdList = ref<string[]>([])

onMounted(() => {
  fetchTaskDetail()
  if (props.showData.taskBid) {
    usersIdList.value = props.showData.taskBid.split(',')
  }
})
</script>

<style lang="less" scoped>
.square-list-item {
  box-sizing: border-box;
  width: 100%;
  padding: 20px 10px;
  border-bottom: 1px solid #eff2f7;
  .item-content {
    display: flex;
    cursor: pointer;
    .left-content {
      margin-right: 20px;
      .el-image {
        width: 220px;
        height: 125px;
        border-radius: 5px;
        overflow: hidden;
        cursor: pointer;
      }
    }
    .right-content {
      width: 100%;
      .content-head {
        display: flex;
        justify-content: space-between;

        .head-title {
          max-width: 460px;
          color: #273444;
          font-size: 17px;
          font-weight: 500;
        }

        .head-title-task {
          max-width: 580px;
          color: #273444;
          font-size: 17px;
          font-weight: 500;
        }

        .tag-container {
          position: relative;
          display: flex;
          align-items: center;
        }

        .tag {
          position: absolute;
          top: 100%;
          right: 0;
          margin-top: 5px;
        }

        .iconfont {
          color: #f74882;
        }
      }
      .content-body {
        margin-top: 5px;
        display: flex;
        flex-wrap: wrap;
        div {
          white-space: nowrap;
          display: flex;
          align-items: flex-start;
          width: 100%;
          text-align: left;
          margin-bottom: 2px;
        }
      }

      .content-foot {
        color: #8796a8;

        span {
          margin-right: 10px;
        }
      }
    }
  }
}
.square-list-item:hover {
  background-color: #f0f2f5;
}
</style>
